package com.yehun.config;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Mybatis二级缓存使用Redis缓存
 * Created by Genius on 2017/4/27 0027.
 */
public class MybatisRedisCache implements Cache {

    private static final Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private String Key;

    public MybatisRedisCache(final String key) {
        if (key == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.Key = key;
        logger.debug("key => " + key);
    }

    @Override
    public String getId() {
        return Key;
    }

    @Override
    public void putObject(Object key, Object value) {
        //getConnection().set(SerializeUtils.serialize(key), SerializeUtils.serialize(value));
        logger.debug("key => " + key.toString());
        RedisDataSource.set(key.toString(), value);
    }

    @Override
    public Object getObject(Object key) {
        return RedisDataSource.get(key.toString());
    }

    @Override
    public Object removeObject(Object key) {
        RedisDataSource.remove(key.toString());
        return null;
    }

    @Override
    public void clear() {

    }

    @Override
    public int getSize() {
        return RedisDataSource.getKeys("*").size();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }
}